package com.lanhai.longheng.impl;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service;

import com.lanhai.longheng.interfaces.ITempData;
import com.lanhai.longheng.utils.Tools;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


@Service 
public class TempDataImpl implements ITempData {
	@Autowired
	JedisPool jedisPool;
	  
	//点位：agvid
	static Map<Integer,Integer> dotForAgvMap=  Collections.synchronizedMap(new HashMap<Integer,Integer>());
	static Object locker =new Object();
  
	/**
	 * 设置某点位的小车
	 */ 
	@Override
	public   void setDotOfAgv(int dotNo, int agvid) {
		synchronized (locker) {

			String mainkey = "dotofAgv";
			Jedis jd = jedisPool.getResource();

			if (agvid > 0) {
				// 先移除小车曾经可能的点位（人工操作的小车）
				for (Entry<Integer, Integer> entry : dotForAgvMap.entrySet()) {
					if (entry.getValue() == agvid) {
						entry.setValue(0);
						jd.hset(mainkey, "" + entry.getKey(), "0");
					}
				}
			}
			// 添加现有的
			dotForAgvMap.put(dotNo, agvid);
			jd.hset(mainkey, "" + dotNo, "" + agvid);
			jd.close();
		}
	}

	/**
	 * 通过点位获取小车
	 */
	@Override
	public int getAgvIdByDotNo(int dotNo) {
		synchronized (locker) { 
			Integer agvid = dotForAgvMap.get(dotNo);
			if (agvid == null) {
				// 不存在，从redis中拿
				String mainkey = "dotofAgv";
				String key = String.format("%d", dotNo);
				Jedis jd = jedisPool.getResource();
				String m = jd.hget(mainkey, key);
				jd.close();

				if (m != null && m.isEmpty() == false) {
					agvid = Tools.strToInt(m);
					dotForAgvMap.put(dotNo, agvid);
					return agvid;
				} else {
					return 0;
				}
			} else {
				return agvid;
			}
		}
	}

	

}
